<template>
  <view class="content-img">
    <eui-nav-bar title="提醒设置" color="#333" rightIcon="" />
  </view>
  <scroll-view scroll-y="true" class="main-view font-size-28" :style="{width:scrollWidth,height:scrollHeight}">
    <view class="padding-top-20">
      <view class="background-color-fff border-radius-20 margin-top-12 padding-left-28">
        <eui-card-input left-icon-type="up" v-model="enable" title="启用提醒" type="switch" style="padding-left: 0" />
      </view>
      <view class="margin-top-20 color-888">声音与振动设置</view>
      <view class="background-color-fff border-radius-20 margin-top-12 padding-left-28">
        <view class="mine-list-item">
          <view class="mine-item-left color-666">音量大小</view>
          <view class="mine-item-right" style="width: 70%">
            <slider style="width: 100%" :value="currentVolume" :max="maxVolume" @change="volumeChanged" @touchmove.stop :activeColor="themeColor"/>
          </view>
        </view>
        <eui-card-input v-model="voiceStyle" :range="voiceStyleList" title="声音风格" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0;" />

        <view class="item">
          <view class="left">
            <view class="color-666">推荐播报次数</view>
          </view>
          <view class="right">
            <eui-button type="min2" minWidth="100" @buttonClick="openRecommendPlayTimes" title="查看" />
          </view>
        </view>
        <eui-card-input v-model="listeningAfterSetting" title="点击试听" type="switch" style="padding-left: 0" />
        <eui-card-input v-model="remindType" :range="remindTypeList" title="消息提醒方式" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0;" />
      </view>
      <view class="margin-top-20 color-888">新单与接单</view>
      <view class="background-color-fff border-radius-20 margin-top-12 padding-left-28">
        <eui-card-input @click="testPlay('newOrder')" v-model="playTimes.newOrder" :range="playTimesList" title="新订单" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('newPreOrder')" v-model="playTimes.newPreOrder" :range="playTimesList" title="新预订单" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('newPickupTask')" v-model="playTimes.newPickupTask" :range="playTimesList" title="新拣货任务" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('newReviewTask')" v-model="playTimes.newReviewTask" :range="playTimesList" title="新复核任务" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderReceiveTimeout')" v-model="playTimes.orderReceiveTimeout" :range="playTimesList" title="接单超时" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
      </view>
      <view class="margin-top-20 color-888">拣货与配送</view>
      <view class="background-color-fff border-radius-20 margin-top-12 padding-left-28">
        <eui-card-input @click="testPlay('orderPickupTimeout')" v-model="playTimes.orderPickupTimeout" :range="playTimesList" title="拣货超时" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderShipperReceiveTimeout')" v-model="playTimes.orderShipperReceiveTimeout" :range="playTimesList" title="骑手接单超时" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderDeliveryException')" v-model="playTimes.orderDeliveryException" :range="playTimesList" title="配送异常" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
      </view>
      <view class="margin-top-20 color-888">取消与退款</view>
      <view class="background-color-fff border-radius-20 margin-top-12 padding-left-28">
        <eui-card-input @click="testPlay('orderCanceled')" v-model="playTimes.orderCanceled" :range="playTimesList" title="订单已取消" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderCancelApply')" v-model="playTimes.orderCancelApply" :range="playTimesList" title="顾客申请取消" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderRefundApply')" v-model="playTimes.orderRefundApply" :range="playTimesList" title="顾客申请退款" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderCancelApplyRepeal')" v-model="playTimes.orderCancelApplyRepeal" :range="playTimesList" title="取消申请撤销" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderRefundApplyRepeal')" v-model="playTimes.orderRefundApplyRepeal" :range="playTimesList" title="退款申请撤销" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('orderRefundCanceled')" v-model="playTimes.orderRefundCanceled" :range="playTimesList" title="订单退款成功" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
      </view>
      <view class="margin-top-20 color-888">售后单</view>
      <view class="background-color-fff border-radius-20 margin-top-12 padding-left-28">
        <eui-card-input @click="testPlay('afsOrderShipperReceiveTimeout')" v-model="playTimes.afsOrderShipperReceiveTimeout" :range="playTimesList" title="骑手接单超时" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
        <eui-card-input @click="testPlay('afsOrderDeliveryException')" v-model="playTimes.afsOrderDeliveryException" :range="playTimesList" title="配送异常" type="selector" placeholder="请选择" alignType="right" rightIconType="right" style="padding-left: 0" />
      </view>
      <view class="padding-bottom-60" :class="[theme]">
        <view class="setting-logOut margin-top-60"  @click="pushNewOrderTest">推送消息测试</view>
      </view>
    </view>
    </scroll-view>
</template>

<script setup lang="ts">
import {onUnmounted, ref, watch} from 'vue';
import {storeToRefs} from "pinia";
import {onLoad, onReady} from '@dcloudio/uni-app';
import {useMainStore} from '../../../../store/modules/store';
import {useReminderStore} from "@/store/reminderStore";
import useVoiceTaskStore from "@/store/useVoiceTaskStore";
import {handleGetVoiceTypeItem, Voice} from "@/common/Voice";
import { useThemeStore } from '@/store/themeStore';
import service from "@/common/service";
import {bcmRequest, getBcmUrl} from "@/hooks/bcmServices";
import terminalUtil from "@/common/terminalUtil";
import BcmEventType from "@/pages/BcmViews/common/BcmEventType";

const themeStore = useThemeStore();
const { theme, themeColor } = storeToRefs(themeStore);

const mainStore = useMainStore();
const reminderStore = useReminderStore();
const voiceTaskStore = useVoiceTaskStore();

const scrollWidth = ref(uni.getSystemInfoSync().windowWidth -20 + 'px');
const scrollHeight = ref(uni.getSystemInfoSync().windowHeight + 'px');

const {enable, remindType, listeningAfterSetting, voiceStyle, playTimes} = storeToRefs(reminderStore);

//音量大小
const maxVolume = 100;
let currentVolume = 0;

// #ifndef H5
currentVolume = plus.device.getVolume() * maxVolume;
console.log("当前音量大小",currentVolume);
// #endif

const voiceStyleList = [
  { value: 'default', text: "标准女声（默认）" },
  { value: 'male', text: "标准男声" },
];
const remindTypeList = [
  { value: 'voice', text: "语音" },
  { value: 'vibrate', text: "振动" },
  { value: 'voiceAndVibrate', text: "语音+振动" },
];

const recommendPlayTimes:any = {
  newOrder: 3,
  newPreOrder: 1,
  newPickupTask: 1,
  newReviewTask: 1,
  orderReceiveTimeout: 1,

  orderPickupTimeout: 1,
  orderShipperReceiveTimeout: 1,
  orderDeliveryException: 3,

  orderCanceled: 1,
  orderCancelApply: 3,
  orderRefundApply: 3,
  orderCancelApplyRepeal: 3,
  orderRefundApplyRepeal: 3,
  orderRefundCanceled:1,

  afsOrderShipperReceiveTimeout: 1,
  afsOrderDeliveryException: 3,
}
const recommendPlayTimesText = '新订单播报' + recommendPlayTimes.newOrder +'次\n'
    + '新订单 播报' + recommendPlayTimes.newOrder +'次\n'
    + '新预订单 播报' + recommendPlayTimes.newPreOrder +'次\n'
    + '新拣货任务 播报' + recommendPlayTimes.newPickupTask +'次\n'
    + '新复核任务 播报' + recommendPlayTimes.newReviewTask +'次\n'
    + '接单超时 播报' + recommendPlayTimes.orderReceiveTimeout +'次\n\n'

    + '拣货超时 播报' + recommendPlayTimes.orderPickupTimeout +'次\n'
    + '骑手接单超时 播报' + recommendPlayTimes.orderShipperReceiveTimeout +'次\n'
    + '配送异常 播报' + recommendPlayTimes.orderDeliveryException +'次\n\n'

    + '订单已取消 播报' + recommendPlayTimes.orderCanceled +'次\n'
    + '顾客申请取消 播报' + recommendPlayTimes.orderCancelApply +'次\n'
    + '顾客申请退款 播报' + recommendPlayTimes.orderRefundApply +'次\n'
    + '订单取消申请撤销 播报'+ recommendPlayTimes.orderCancelApplyRepeal +'次\n'
    + '退款申请撤销 播报' + recommendPlayTimes.orderRefundApplyRepeal +'次\n'
    + '订单发起退款成功 播报'+ recommendPlayTimes.orderRefundCanceled +'次\n\n'

    + '售后单骑手接单超时 播报' + recommendPlayTimes.afsOrderShipperReceiveTimeout +'次\n'
    + '售后单配送异常 播报' + recommendPlayTimes.afsOrderDeliveryException +'次\n';

const playTimesList = [
  { value: 0, text: "不播报" },
  { value: 1, text: "播报1次" },
  { value: 2, text: "播报2次" },
  { value: 3, text: "播报3次" },
  { value: 9, text: "播报9次" },
];

const volumeChanged = (res:any) => {
  console.log("res",res);
  // #ifndef H5
  let volume = res.detail.value/maxVolume;
  console.log("volume", volume);
  plus.device.setVolume(parseFloat(volume.toFixed(2)));
  // #endif
}

const testPlay = (type:string) => {
  console.log("res",type);
  if( !reminderStore.$state.listeningAfterSetting ){
    return ;
  }
  let item = handleGetVoiceTypeItem(type);
  voiceTaskStore.addVoiceTask({
    id: 1,
    remindType: reminderStore.$state.remindType,
    path: 'static/audio/' + reminderStore.$state.voiceStyle + '/' + item?.file,
    times: reminderStore.$state.playTimes[type]
  })
}

watch(enable, (newValue, oldValue) => {
  reminderStore.setEnable(newValue);
});

// input的selector不支持@change属性，使用watch处理
watch(voiceStyle, (newValue, oldValue) => {
  reminderStore.setVoiceStyle(newValue);
});

watch(playTimes, (newValue, oldValue) => {
  console.log("playTimes", playTimes);
  reminderStore.setPlayTimes(newValue);
});

const openRecommendPlayTimes = ()=>{
  uni.showModal({
    title: '推荐播报次数',
    content: recommendPlayTimesText,
    confirmText: '使用推荐',
    success:  (res) => {
      if (res.confirm) {
        reminderStore.setPlayTimes(recommendPlayTimes)
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  });
}

const pushNewOrderTest = () => {
  let loginInfo = mainStore.loginInfo;
  let socketUrl = bcmUrl.wsApi.startsWith("http") || bcmUrl.wsApi.startsWith("ws") ? bcmUrl.wsApi.replace("http", "ws") : ''; //支持https 替换为 wss
  // const wsUrl = socketUrl + '?access_token=' + loginInfo.access_token;
  const terminalId = terminalUtil.getTerminalId();
  const pushMode = service.getStorageSync('pushMode');
  let curStore = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
  let curStoreHier = loginInfo?.sDefaultStoreHier ? loginInfo.sDefaultStoreHier : loginInfo.sUserStoreHier;

  let flag = true;
  let textArray = [];
  // 推送模式不等于2 || socketUrl为空 || 机构层级不等于分店 || 门店编码为空 || loginInfo.access_token 为空
  if (pushMode != '2') {
    flag = false;
    textArray.push('设置页面的"推送方式"不是"实时"');
  }
  if (!socketUrl) {
    flag = false;
    textArray.push('未配置业务中台接口地址');
  }
  if (!curStore) {
    flag = false;
    textArray.push('未获取到当前门店信息');
  }
  if (curStoreHier != '2') {
    flag = false;
    textArray.push('当前门店不是分店/配送中心');
  }
  if (!terminalId) {
    flag = false;
    textArray.push('未获取到设备的终端ID');
  }
  if (!loginInfo.access_token) {
    flag = false;
    textArray.push('登录异常，access_token为空');
  }

  if(!flag){
    uni.showModal({
      title: '测试失败，原因如下',
      content: textArray.map((item, index) => (index+1)+'.' + item).join('\n'),
      confirmText: '确定',
      showCancel :false,
      success:  (res) => {
      }
    });
    return;
  }

  testWebSocketAction({
    uniqueKey: '消息提醒',
    methodName: 'TestWebSocket'
  },{
    storeCode: curStore,
    terminalType: 'APP',
    terminalId: terminalId,
  },'',false);
}

onReady(()=>{
  uni.getSystemInfo({
    success: function(res) {
      const userInfoPage = uni.createSelectorQuery().select(".content-img");
      userInfoPage.boundingClientRect(function(data:any) {
        scrollHeight.value = (res.windowHeight - data.height)+'px';
      }).exec()
    }
  });
})

onLoad(async () => {
  uni.$on(BcmEventType.TEST_WEB_SOCKET, () => {
    console.warn("成功");
    uni.showToast({
      title: "消息测试成功",
      icon: 'success'
    });
  })
})

onUnmounted(() => {
  uni.$off(BcmEventType.TEST_WEB_SOCKET)
})

const bcmUrl = getBcmUrl()
const testWebSocketAction = async function (a: {
  uniqueKey: string,
  methodName: string
}, params: any = undefined, text = '', popup = false, fn: any = undefined) {
  service.enjoyShowLoading('正在加载...');
  const response = await bcmRequest(bcmUrl.managerApi, a.uniqueKey, a.methodName, params);
  service.enjoyHideLoading();
  if (text) {
    uni.showToast({
      title: text,
      icon: 'none'
    });
  }
  if (popup) {
    close()
  }
  if (fn) {
    fn()
  }
  if (params) {
    return response
  }
}
</script>

<style lang="scss" scoped>
@import '@/main.scss';

.content-img {
  background-color: #FFFFFF;
  background-repeat: no-repeat;
  width: 100%;
}

.main-view {
  flex: 1;
  flex-direction: column;
  padding: 0 20rpx;
  background-color: #f2f2f2;
}

.flex {
  display: flex;
}

.font-size-28 {
  font-size: 28rpx;
}

.setting-logOut {
  display: flex;
  width: 100%;
  height: 50px;
  background-color: #fff;
  border-radius: 10px;
  justify-content: center;
  align-items: center;
  color: var(--theme-color);
  font-size: 14px;
}

.padding-all-28 {
  padding: 28rpx;
}

.background-color-fff {
  background-color: #fff;
}

.border-radius-20 {
  border-radius: 20rpx;
}

.padding-top-20 {
  margin-top: 20rpx;
}
.padding-bottom-60{
  padding-bottom: 60rpx;
}

.margin-top-20 {
  margin-top: 20rpx;
}

.margin-top-60 {
  margin-top: 60rpx;
}

.margin-top-12 {
  margin-top: 12rpx;
}

.color-888 {
  color: rgba(136, 136, 136, 1);
}
.color-666 {
  color: #666;
}
.main-theme {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  margin-right: 32rpx;
  position: relative;
}

.main-theme-1 {
  background-color: rgba(2, 183, 230, 1);
}

.main-theme-2 {
  background-color: #FF6430;
}

.main-body .main-theme:last-child {
  margin-right: 0rpx;
}

.main-theme-sel {
  width: 25px;
  height: 25px;
  background: #ffffff;
  clip-path: polygon(100% 10%, 100% 100%, 10% 100%);
  position: absolute;
  bottom: 0;
  right: 0;
}

.main-theme-icon {
  position: absolute;
  bottom: 0;
  right: 0;
}

.overflow-hidden {
  overflow: hidden;
}

.padding-left-28 {
  padding-left: 28rpx;
}
.item {
  border-bottom: 0.03125rem solid rgb(238, 238, 238);
  padding: 0.75rem 0.875rem 0.75rem 0;
  display: flex;
  flex-direction: row;
  width: 100%;
  box-sizing: border-box;
}
.item .left {
  flex: 1;
  align-self: center;
}
.item .right{
  display: flex;
  justify-content: center;
  align-items: center;
}

.mine-list-item {
  height: 45px;
  line-height: 45px;
  border-bottom: 0.03125rem solid rgb(238, 238, 238);
  display: flex;
  flex-direction: row;
  align-items: center;
}

.mine-list-item .mine-item-left {
  width: 270 rpx;
}

.mine-list-item .mine-item-right {
  font-size: 14px;
  color: #aaa;
  display: flex;
  margin-left: auto;
}
.m-card-input-view{
  background-color: initial;
}
</style>